export const chatStream = async (question, onMessage, onError, onComplete) => {
  let retryCount = 0;
  const maxRetries = 3;
  let isCompleted = false;
  // console.log("用户发起的question:", question);

  // 创建 EventSource
  const createEventSource = () => {
    try {
      // 创建 EventSource事件监听对象
      const eventSource = new EventSource(
        `/api/chat/chat_stream/?question=${encodeURIComponent(question)}`
      );

      // 监听处理连接打开事件
      eventSource.onopen = () => {
        console.log("SSE 连接已建立");
        retryCount = 0; // 重置重试计数
      };

      // 监听后端主动处理消息事件
      eventSource.onmessage = (event) => {
        try {
          const data = JSON.parse(event.data);

          // 检查是否是完成标记
          if (data.content === "[DONE]") {
            console.log("收到完成信号");
            isCompleted = true;
            eventSource.close();
            onComplete();
            return;
          }

          onMessage(data.content);
        } catch (e) {
          console.error("解析消息数据失败:", e);
          onError(e);
        }
      };
      // 监听处理错误事件
      eventSource.onerror = (error) => {
        console.log("SSE 错误:", error);

        // 如果已经完成，不要重试
        if (isCompleted) {
          console.log("流已完成，不进行重试");
          return;
        }

        if (retryCount < maxRetries) {
          retryCount++;
          console.log(`尝试重新连接 (${retryCount}/${maxRetries})...`);
          eventSource.close();
          setTimeout(() => createEventSource(), 1000 * retryCount); // 指数退避
        } else {
          console.error("达到最大重试次数，停止重试");
          onError(error);
          eventSource.close();
        }
      };

      return eventSource;
    } catch (error) {
      console.error("创建 EventSource 失败:", error);
      onError(error);
      return null;
    }
  };

  // 创建并返回清理函数
  const eventSource = createEventSource();
  return () => {
    if (eventSource) {
      console.log("清理 EventSource 连接");
      eventSource.close();
    }
  };
};
